//
// a Date/Time server
// conn: RFCOMM
//

import java.io.*;
import javax.bluetooth.*;
import javax.bluetooth.UUID;
import javax.microedition.io.*;
import java.util.*;

public class RFDateServ {
	public static void main(String args[]) {
		LocalDevice localdev = null;
		try {
			localdev = LocalDevice.getLocalDevice();
		} catch (BluetoothStateException e) {
			System.out.println("ERROR: cannot access local device");
			System.exit(1);
		}

		// show an example usage of getProperty.
		// System.out.println("MTU: " + localdev.getProperty(
		// "bluetooth.l2cap.receiveMTU.max"));

		UUID uuid = new UUID("102030405060708090A0B0C0D0E0F011", false);
		String url = "btspp://localhost:" + uuid.toString();

		try {
			// 1. create service record
			StreamConnectionNotifier n = (StreamConnectionNotifier) Connector
					.open(url);

			// 2. obtain the service record
			// set ServiceRecrod ServiceAvailability (0x0008) attribute to
			// indicate our service is available
			// 0xFF indicate fully available status
			// This operation is optional
			ServiceRecord record = localdev.getRecord(n);
			record.setAttributeValue(0x0008, new DataElement(
					DataElement.U_INT_1, 0xFF));

			System.out.println("Waiting to be connected...");

			// 3.ready to accept connection: will block until a client connects
			StreamConnection conn = n.acceptAndOpen();

			// send and receive data
			String message = new Date().toString();
			InputStream is = conn.openInputStream();
			OutputStream os = conn.openOutputStream();
			os.write(message.getBytes());
			byte[] rbuf = new byte[100];
			is.read(rbuf);
			System.out.println("Received: " + new String(rbuf));
			is.close();
			os.close();
			conn.close();
		} catch (Exception e) {
			System.out.println("ERROR: connection failed.");
		}
	}
}
